package uk.co.agileworks.bidpirate.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import uk.co.agileworks.bidpirate.model.Bid;
import uk.co.agileworks.bidpirate.model.Item;
import uk.co.agileworks.bidpirate.service.ServiceException;

@Controller
@RequestMapping("/findItem.html")
@SessionAttributes("bid")
public final class FindItemForm extends ControllerHelper {

	static final String FORM = "findItem";
	static final String SUCCESS = "redirect:/addBid.html";

	@Resource
	private Validator<Bid> bidValidator;

	@RequestMapping(method = RequestMethod.GET)
	public void getForm(Model model) {
		Bid bid = new Bid();
		bid.setUser(getUserSession().getUser());
		model.addAttribute(bid);
	}

	@RequestMapping(method = RequestMethod.POST)
	public String postForm(@ModelAttribute Bid bid, Errors errors) {
		try {
			long itemNumber = getEbayFacade().extractItemNumber(bid.getItemNumberOrUrl());
			String itemUrl = getEbayFacade().getItemUrl(itemNumber);
			Item item = getEbayFacade().parseItem(itemUrl);
			LOGGER.info("Parsed item. {" + item + "}");
			bid.setItem(item);
			bidValidator.validate(bid, errors);
		} catch (ServiceException e) {
			errors.reject(e.getMessage());
		}
		return errors.hasErrors() ? FORM : SUCCESS;
	}

}
